﻿using System;
using System.IO;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Jiubang.IO;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Jiubang.UnitTest.IO {
    /// <summary>
    /// LazyFileSystemWatcherTester 的摘要说明
    /// </summary>
    [TestClass]
    public class LazyFileSystemWatcherTester {
        readonly string path = System.AppDomain.CurrentDomain.BaseDirectory;
        const string Filter = "test.txt";
        readonly System.Threading.AutoResetEvent are = new AutoResetEvent(false);

        public LazyFileSystemWatcherTester() {
            //
            //TODO: 在此处添加构造函数逻辑
            //
        }

        private TestContext testContextInstance;

        /// <summary>
        ///获取或设置测试上下文，该上下文提供
        ///有关当前测试运行及其功能的信息。
        ///</summary>
        public TestContext TestContext {
            get {
                return testContextInstance;
            }
            set {
                testContextInstance = value;
            }
        }

        #region 附加测试属性
        //
        // 编写测试时，还可使用以下附加属性:
        //
        // 在运行类中的第一个测试之前使用 ClassInitialize 运行代码
        // [ClassInitialize()]
        // public static void MyClassInitialize(TestContext testContext) { }
        //
        // 在类中的所有测试都已运行之后使用 ClassCleanup 运行代码
        // [ClassCleanup()]
        // public static void MyClassCleanup() { }
        //
        // 在运行每个测试之前，使用 TestInitialize 来运行代码
        // [TestInitialize()]
        // public void MyTestInitialize() { }
        //
        // 在每个测试运行完之后，使用 TestCleanup 来运行代码
        // [TestCleanup()]
        // public void MyTestCleanup() { }
        //
        #endregion

        [TestMethod]
        public void EventTest() {

            var watcher = new LazyFileSystemWatcher(path, Filter, WatcherChangeTypes.Created | WatcherChangeTypes.Changed | WatcherChangeTypes.Deleted);
            watcher.Changed += new LazyFileSystemWatcher.Handler(WatcherChanged);
            watcher.EnableRaisingEvents = true;

            string fileFullName = path + Path.DirectorySeparatorChar + Filter;
            using (var stream = File.Create(fileFullName)) {
                stream.Flush();
                stream.WriteByte(1);
                stream.Flush();
                stream.WriteByte(2);
            }
            File.Delete(fileFullName);

            Assert.IsTrue(are.WaitOne(400)); 
        }

        void WatcherChanged(LazyFileSystemWatcher sender, LazyFileSystemWatcher.EventArgument e){
            Assert.AreEqual(WatcherChangeTypes.Created, e.History.First.Value);
            Assert.AreEqual(WatcherChangeTypes.Changed, e.History.First.Next.Value);
            Assert.AreEqual(WatcherChangeTypes.Deleted, e.History.Last.Value);

            are.Set();
        }

    }
}
